package com.sunshine.ssm.controller.system;

import com.google.code.kaptcha.Constants;
import com.sunshine.ssm.entity.UserInfo;
import com.sunshine.ssm.entity.vo.Email;
import com.sunshine.ssm.system.IEmailService;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by WeiHong on 2016/12/6.
 */
@Controller
public class LoginController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private IEmailService emailService;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @RequestMapping(value = "/")
    public String index() {
        return "/login";
    }

    /**
     * 跳转到主页
     *
     * @param mv
     * @return
     */
    @RequestMapping(value = "/home")
    public ModelAndView success(ModelAndView mv) {
        if (SecurityUtils.getSubject().isAuthenticated() || SecurityUtils.getSubject().isRemembered()){
            mv.setViewName("/home");
        }else {
            mv.setViewName("/login");
        }


        return mv;
    }

    @RequestMapping(value = "/unauthor")
    public ModelAndView unauthor() {
        ModelAndView mv = new ModelAndView("/unauthor");
        return mv;
    }

    @RequestMapping(value = "/login")
    public String login(UserInfo info, HttpServletRequest request) {
        HttpSession session1 = request.getSession();
        String code = (String) session1.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        UsernamePasswordToken token = new UsernamePasswordToken(info.getUserName(), info.getPassword());
        token.setRememberMe(true);
        try {
            subject.login(token);
            session.setAttribute("userInfo", info);
            return "redirect:/home";
        } catch (ExcessiveAttemptsException eae) {
            LOGGER.error("登陆失败！", eae);
            session.setAttribute("errorMsg", "尝试登陆超过5次，锁定2分钟！");
        } catch (AuthenticationException e) {
            LOGGER.error("登陆失败！", e);
            session.setAttribute("errorMsg", "用户名或者密码错误（或者您未登录）请重新登陆！");
        }
        return "redirect:/";
    }

    @RequestMapping(value = "/logout")
    public String logout() throws IOException {
        SecurityUtils.getSubject().logout();
        return "redirect:/";
    }


    @RequestMapping(value = "/sendMailTest")
    public void sendMailTest() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss S");
        LOGGER.debug("邮件发送测试开始！" + sdf.format(new Date()));
        long startTime = System.currentTimeMillis();
        int count = 0;
        for (int i = 0; i < 10; i++) {
            count++;
            Email email = new Email();
            email.setFrom("weihong0755@163.com");
            email.setTo("719123476@qq.com");
            email.setUsername("weihong0755");
            email.setSubject("这是一个邮件标题测试邮件");
            email.setDetails(this.getMailText());
            emailService.sendMail(email);
        }
        LOGGER.debug("邮件发送测试结束！" + sdf.format(new Date()));
        System.out.println("总共发送：" + count);
        long endTime = System.currentTimeMillis();
        System.out.println("程序运行总时间：" + (endTime - startTime));
    }


    /**
     * 获取模板并将内容输出模板
     *
     * @return
     */
    public String getMailText() {
        String html = "";
        try {
            Map map = new HashMap();
            map.put("userName", "张晓明");
            map.put("userId", "B00089999");
            map.put("password", "123456");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
            map.put("sendTime", sdf.format(new Date()));
            // 装载模板
            Template tpl = this.freeMarkerConfigurer.getConfiguration().getTemplate("forgetPassword.ftl");
            // 加入map到模板中 输出对应变量
            html = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
        } catch (IOException e) {
            LOGGER.error("加载模板异常", e);
        } catch (TemplateException e) {
            LOGGER.error("模板装载异常", e);
        }
        return html;
    }

}
